package com.tom.zojbackendjudgeservice.message;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

import static com.tom.zojbackendcommon.constant.RabbitMqConstant.*;

@Slf4j
public class InitMessageQueue {

    /**
     * 初始化正常队列和死信队列
     */
    public static void init() {
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("47.120.24.66");
            factory.setPort(5672);
            factory.setUsername("tom");
            factory.setPassword("123456");
            Connection connection = factory.newConnection();
            if(connection == null) {
                System.out.println();
                throw new RuntimeException("连接失败!");
            }
            Channel channel = connection.createChannel();

        //创建死信交换机、死信队列，并绑定
            channel.exchangeDeclare(EXCHANGE_DIRECT_DEAD,"direct");

            channel.queueDeclare(QUEUE_NAME_DEAD,true,false,false,null);

            channel.queueBind(QUEUE_NAME_DEAD,EXCHANGE_DIRECT_DEAD,ROUTING_KEY_DEAD);

        //创建正常队列
            //创建交换机
            channel.exchangeDeclare(EXCHANGE_DIRECT,"direct");

            //创建正常队列绑定死信队列信息
            Map<String, Object> params = new HashMap<>();
            params.put("x-dead-letter-exchange",EXCHANGE_DIRECT_DEAD);
            params.put("x-dead-letter-routing-key",ROUTING_KEY_DEAD);

            //创建正常队列
            channel.queueDeclare(QUEUE_NAME,true,false,false,params);

            //绑定交换机和队列
            channel.queueBind(QUEUE_NAME,EXCHANGE_DIRECT,ROUTING_KEY);

            log.info("初始化消息队列成功!");

        }catch (Exception e){
            log.error("初始化消息队列失败!");
            throw new RuntimeException(e+"初始化消息队列失败!");
        }
    }

    public static void main(String[] args) {
        init();
    }
}
